package me.spring.cloud.common.components.poi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

public class EasypoiUtil {

  /**
   * 创建excel表头
   *
   * @param colEntityInfo 表头信息
   * @Return
   */
  public static ExcelExportEntity createCol(ColEntityInfo colEntityInfo) {
    ExcelExportEntity excelExportEntity = new ExcelExportEntity(colEntityInfo.getColName(),
        colEntityInfo.getColFiled());
    excelExportEntity.setNeedMerge(colEntityInfo.isNeedMerge());
    return excelExportEntity;
  }

  /**
   * 创建复杂表头
   *
   * @param colGroupInfo 一级表头
   * @param colEntityInfoList 二级表头列表
   * @Return
   */
  public static ExcelExportEntity createColGroup(ColEntityInfo colGroupInfo, List<ColEntityInfo> colEntityInfoList) {
    ExcelExportEntity deliColGroup = new ExcelExportEntity(colGroupInfo.getColName(), colGroupInfo.getColFiled());
    List<ExcelExportEntity> deliColList = new ArrayList<>();
    colEntityInfoList.stream().forEachOrdered(col -> {
      deliColList.add(createCol(col));
    });
    deliColGroup.setList(deliColList);
    return deliColGroup;
  }


  public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
      boolean isCreateHeader, HttpServletResponse response) {
    ExportParams exportParams = new ExportParams(title, sheetName);
    exportParams.setCreateHeadRows(isCreateHeader);
    defaultExport(list, pojoClass, fileName, exportParams, response);

  }

  public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
      HttpServletResponse response) {
    defaultExport(list, pojoClass, fileName, new ExportParams(title, sheetName), response);
  }

  public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
    defaultExport(list, fileName, response);
  }

  public static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,
      HttpServletResponse response) {
    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
    if (workbook != null) {
      downLoadExcel(fileName, response, workbook);
    }
  }

  /**
   * 自定义表头导出数据
   *
   * @param list 数据
   * @param colList 表头数据
   * @param fileName 文件名称
   * @param exportParams 大表头及sheet名称
   * @param response
   */
  public static void defaultExport(List<?> list, List<ExcelExportEntity> colList, String fileName,
      ExportParams exportParams, HttpServletResponse response) {
    Workbook workbook = ExcelExportUtil.exportExcel(exportParams, colList, list);
    if (workbook != null) {
      downLoadExcel(fileName, response, workbook);
    }
  }

  public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
    try {
      response.setCharacterEncoding("UTF-8");
      response.setHeader("content-Type", "application/vnd.ms-excel");
      response.setHeader("Content-Disposition",
          "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
      workbook.write(response.getOutputStream());
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage());
    }
  }

  private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
    Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
    if (workbook != null) {
      downLoadExcel(fileName, response, workbook);
    }
  }

  public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
    if (StringUtils.isBlank(filePath)) {
      return null;
    }
    ImportParams params = new ImportParams();
    params.setTitleRows(titleRows);
    params.setHeadRows(headerRows);
    List<T> list = null;
    try {
      list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
    } catch (NoSuchElementException e) {
      throw new RuntimeException("模板不能为空");
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return list;
  }

  public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
    if (file == null) {
      return null;
    }
    ImportParams params = new ImportParams();
    params.setTitleRows(titleRows);
    params.setHeadRows(headerRows);
    List<T> list = null;
    try {
      list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
    } catch (NoSuchElementException e) {
      throw new RuntimeException("excel文件不能为空");
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return list;
  }

  /**
   * @Description: 创建多sheets
   * @Param: [map, pojoClass]
   * @Return: org.apache.poi.ss.usermodel.Workbook
   * @Author: wqh
   * @Date: 2019/1/9 10:57
   */
  public static Workbook exportSheets(Map map, Class<?> pojoClass) {
    List<Map<String, Object>> sheetsList = new ArrayList<>();
    for (Object key : map.keySet()) {
      Map dataMap = new HashMap<>(10);
      dataMap.put("title", new ExportParams(key.toString(), map.size() > 1 ? key.toString() : "Sheet0"));
      dataMap.put("entity", pojoClass);
      dataMap.put("data", map.get(key));
      sheetsList.add(dataMap);
    }
    return ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF);
  }
}
